<template>
	<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item label="关键词" prop="keyword">
				<el-input v-model="state.keyword" placeholder="请输入" clearable>
					<template #prepend>
						<el-select v-model="state.keyType" placeholder="请选择" style="width: 100px; min-width: 100px">
							<el-option label="标准编号" value="1" />
							<el-option label="标准名称" value="2" />
							<el-option label="项目负责人" value="3" />
							<el-option label="联系人" value="4" />
							<el-option label="提交人" value="5" />
						</el-select>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="复审阶段" prop="reviewStage">
				<el-select v-model="state.queryForm.reviewStage" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in reviewStage" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="复审状态" prop="reviewStatus">
				<el-select v-model="state.queryForm.reviewStatus" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in reviewStatus" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="复审结论" prop="remark">
				<el-select v-model="state.queryForm.remark" multiple placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in reviewResult" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="search()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>
	<el-card>
		<el-form :inline="true" style="text-align: right" class="anniu">
			<el-form-item v-auth="'M003_Submit'">
				<el-button type="primary" :disabled="!hasPermission" @click="submitHandle()">提交</el-button>
			</el-form-item>
			<!-- <el-form-item>
				<el-button type="primary" @click="createListHandle()">复审清单</el-button>
			</el-form-item> -->
			<el-form-item v-auth="'M003_Export'">
				<el-button type="primary" @click="exportHandle()">导出项目</el-button>
			</el-form-item>
			<el-form-item v-auth="'M003_ApproveFile'">
				<el-button type="primary" :disabled="!hasUploadPermission" @click="uploadFileHandle()">审批附件</el-button>
			</el-form-item>
			<el-form-item v-auth="'M003_ReviewAnalysis'">
				<el-button type="primary" @click="addOrUpdateHandle()">复审分析</el-button>
			</el-form-item>
			<el-form-item v-auth="'M003_CancelPublish'">
				<el-button type="primary" :disabled="!hasPublish" @click="cancelHandle()">取消发布</el-button>
			</el-form-item>
			<el-form-item v-auth="'M001_RePublish'">
				<el-button type="primary" :disabled="!hasUnPublish" @click="republishHandle()">重新发布</el-button>
			</el-form-item>
		</el-form>
		<el-table
			ref="multipleTableRef"
			v-loading="state.dataListLoading"
			:data="dataList"
			stripe
			border
			:resizable="true"
			@selection-change="selectionChangeHandle"
		>
			<el-table-column type="selection" header-align="center" align="center" width="55" fixed="left" />
			<el-table-column prop="index" label="序号" header-align="center" align="center" width="60" fixed="left"></el-table-column>
			<el-table-column prop="reviewYear" label="所属年份" header-align="center" align="center" width="110" sortable></el-table-column>
			<el-table-column
				prop="standardNumber"
				label="标准编号"
				header-align="center"
				align="center"
				width="140"
				fixed="left"
				sortable
			></el-table-column>
			<el-table-column prop="standardProjectName" label="标准名称" header-align="center" align="center" width="120" sortable></el-table-column>
			<el-table-column prop="contactName" label="联系人" header-align="center" align="center" width="110" sortable></el-table-column>
			<el-table-column prop="contactTel" label="联系电话" header-align="center" align="center" width="120" sortable></el-table-column>
			<el-table-column prop="projectLeader" label="项目负责人" header-align="center" align="center" width="140" sortable></el-table-column>
			<el-table-column prop="editorUnitName" label="主编单位" header-align="center" align="center" width="180" sortable></el-table-column>
			<el-table-column prop="reviewType" label="复审来源" header-align="center" align="center" width="110" sortable>
				<template #default="scope">
					<span>{{ scope.row.reviewType == 0 ? '计划内' : '计划外' }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="reviewStage" label="复审阶段" header-align="center" align="center" width="110" sortable>
				<template #default="scope">
					<span>{{ reviewStage.filter(item => item.code === scope.row.reviewStage)[0].name }}</span>
					<!-- <span v-if="scope.row.reviewStage == 4">审核完毕</span> -->
				</template>
			</el-table-column>
			<el-table-column prop="reviewStatus" label="复审状态" header-align="center" align="center" width="110" sortable>
				<template #default="scope">
					<span>{{ dictionaryStore.getDictionaryName('T015', scope.row.reviewStatus) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="主管部门审核" header-align="center" align="center" width="150" sortable>
				<template
					v-if="
						userStore.user.roleCode.includes('SHZG') || userStore.user.roleCode.includes('SYADMIN') || userStore.user.roleCode.includes('ZZADMIN')
					"
					#default="scope"
				>
					<el-select v-if="scope.row.auditResultF && scope.row.permission != 1" v-model="scope.row.auditResultF" disabled>
						<el-option v-for="item in handleResult1" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
					</el-select>
					<el-select v-if="scope.row.reviewStage == 1 && scope.row.permission == 1" v-model="scope.row.status">
						<el-option v-for="item in handleResult1" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
					</el-select>
				</template>
				<el-table-column
					v-if="!userStore.user.roleCode.includes('SHZG')"
					prop="auditResultF"
					label="主管部门1"
					width="170"
					header-align="center"
					align="center"
					sortable
				>
					<template #default="scope">
						<el-select v-if="scope.row.auditResultF" v-model="scope.row.auditResultF" disabled>
							<el-option v-for="item in handleResult1" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column
					v-if="!userStore.user.roleCode.includes('SHZG')"
					prop="auditResultS"
					label="主管部门2"
					width="170"
					header-align="center"
					align="center"
					sortable
				>
					<template #default="scope">
						<el-select v-if="scope.row.auditResultS" v-model="scope.row.auditResultS" disabled>
							<el-option v-for="item in handleResult1" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column
					v-if="!userStore.user.roleCode.includes('SHZG')"
					prop="auditResultT"
					label="主管部门3"
					width="170"
					header-align="center"
					align="center"
					sortable
				>
					<template #default="scope">
						<el-select v-if="scope.row.auditResultT" v-model="scope.row.auditResultT" disabled>
							<el-option v-for="item in handleResult1" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
						</el-select>
					</template>
				</el-table-column>
			</el-table-column>
			<el-table-column
				v-if="!userStore.user.roleCode.includes('SHZG')"
				prop="auditResultExp"
				label="专家及总站意见"
				width="170"
				header-align="center"
				align="center"
				sortable
			>
				<template #default="scope">
					<el-select v-if="scope.row.reviewStage > 1 && scope.row.auditResultExp != null" v-model="scope.row.auditResultExp" disabled>
						<el-option v-for="item in handleResult1" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
					</el-select>
					<el-select v-if="scope.row.reviewStage == 2 && scope.row.permission == 1" v-model="scope.row.status">
						<el-option v-for="item in handleResult1" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
					</el-select>
				</template>
			</el-table-column>
			<el-table-column
				v-if="!userStore.user.roleCode.includes('SHZG')"
				prop="auditResultCom"
				label="住建委意见"
				width="170"
				header-align="center"
				align="center"
				sortable
			>
				<template #default="scope">
					<el-select v-if="scope.row.reviewStage > 2 && scope.row.auditResultCom != null" v-model="scope.row.auditResultCom" disabled>
						<el-option v-for="item in reviewResult" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
					</el-select>
					<el-select v-if="scope.row.reviewStage == 3 && scope.row.permission == 1" v-model="scope.row.status">
						<el-option v-for="item in reviewResult" :key="item.code" :label="item.name" :value="item.code">{{ item.name }}</el-option>
					</el-select>
				</template>
			</el-table-column>
			<el-table-column prop="remark" label="复审结论" header-align="center" align="center" min-width="200" sortable>
				<template #default="scope">
					<span v-if="scope.row.remark">{{ reviewResult.filter(item => item.code === scope.row.remark)[0].name }}</span>
					<!-- <span>{{ scope.row.remark }}</span> -->
				</template>
			</el-table-column>
			<el-table-column prop="reviewApproveDocument" label="复审结论批文" header-align="center" align="center" width="200" sortable>
				<template #default="scope">
					<div v-if="scope.row.applyStatus != '4' && scope.row.reviewStatus == '3'">
						<span
							v-for="item in scope.row.reviewApproveDocument"
							:key="item.id"
							type="success"
							style="margin-left: 5px; cursor: pointer; text-decoration: underline"
							@click="handleUploadPdfPreview(item)"
						>
							{{ item.fileRealName }}.{{ item.fileExtName }}
						</span>
					</div>
					<div v-else></div>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="130">
				<template #default="scope">
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="detailHandle(scope.row)">
						<View />
					</el-icon>
					<el-icon
						v-if="(scope.row.permission == '1' || scope.row.permission == '2') && Number(scope.row.reviewStage) != 4"
						v-auth="'M003_ReviewComments'"
						:size="16"
						color="#1491FF"
						title="审核意见"
						style="cursor: pointer; margin: 0 6px"
						@click="toComment(scope.row, false)"
					>
						<ChatLineSquare />
					</el-icon>
					<el-icon
						v-if="scope.row.permission == '1' && scope.row.reviewStage == '1'"
						v-auth="'M003_ReviewReturn'"
						:size="16"
						color="#1491FF"
						title="退回"
						style="cursor: pointer; margin: 0 6px"
						@click="handleReturnBack(scope.row)"
					>
						<FolderDelete />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
		<cmDialog v-model="showUploadDialog" modal-title="复审审核文件批量上传" model-width="1000px">
			<el-form ref="optionsFormRef1" :model="optionsInfo" :rules="optionsRules" label-width="130px">
				<el-row>
					<el-form-item label="意见附件类型" style="width: 100%">
						<el-radio-group v-model="optionsInfo.stage" @change="uploadTypeChange">
							<el-radio v-for="(item, index) in optionsList" :key="index" :value="item.value" size="large">{{ item.name }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="意见批文(pdf)" style="width: 100%" prop="filesRecordList">
						<el-upload
							ref="uploadPdfRef"
							drag
							:action="uploadApi"
							:headers="uploadHeaders"
							:data="uploadData"
							accept=".pdf"
							:on-success="handleUploadSuccess"
							:on-remove="handleUploadRemove"
							:file-list="optionsInfo.filesRecordList"
							:before-upload="beforeUploadPdf"
							:on-preview="handleUploadPdfPreview"
							:on-change="handleChange"
						>
							<el-icon class="el-icon--upload"><upload-filled /></el-icon>
							<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
						</el-upload>
					</el-form-item>
				</el-row>
				<el-row v-if="currentStage == '3' || isRepublish">
					<el-form-item label="批文年度" prop="approvalFileYear">
						<el-date-picker
							v-model="optionsInfo.approvalFileYear"
							type="year"
							format="YYYY"
							value-format="YYYY"
							placeholder="选择年份"
							style="width: 240px"
						/>
					</el-form-item>
					<el-form-item label="文号" prop="approvalFileNumber">
						<el-input v-model="optionsInfo.approvalFileNumber" type="number" placeholder="请输入" style="width: 240px" />
					</el-form-item>
				</el-row>
			</el-form>
			<el-table :data="selectList" border size="small">
				<el-table-column label="序号" type="index" width="50" align="center" />
				<el-table-column prop="standardNumber" label="标准编号" header-align="center" align="center"></el-table-column>
				<el-table-column prop="standardProjectName" label="标准名称" header-align="center" align="center"></el-table-column>
				<el-table-column prop="editorUnitName" label="主编单位" header-align="center" align="center"></el-table-column>
				<el-table-column prop="projectLeader" label="项目负责人" header-align="center" align="center" width="100"></el-table-column>
				<el-table-column prop="reviewYear" label="所属年份" header-align="center" align="center" width="80"></el-table-column>
				<el-table-column prop="reviewStage" label="复审阶段" header-align="center" align="center" width="100">
					<template #default="scope">
						<span>{{ reviewStage.filter(item => item.code === scope.row.reviewStage)[0].name }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="reviewStatus" label="复审状态" header-align="center" align="center" width="80">
					<template #default="scope">
						<span>{{ dictionaryStore.getDictionaryName('T015', scope.row.reviewStatus) }}</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="userStore.user.roleCode.includes('SHZG')"
					prop="hasDocument"
					label="是否有管理文件，具体措施"
					header-align="center"
					align="center"
				>
					<template #default="scope">
						<el-radio-group v-model="scope.row.hasDocument" disabled>
							<el-radio :value="'1'">有</el-radio>
							<el-radio :value="'0'">无</el-radio>
						</el-radio-group>
					</template>
				</el-table-column>
				<el-table-column v-if="userStore.user.roleCode.includes('SHZG')" label="具体内容" header-align="center" align="center" width="80">
					<template #default="scope">
						<el-icon
							v-if="scope.row.permission == '1' || scope.row.permission == '2'"
							v-auth="'M003_ReviewComments'"
							:size="16"
							color="#1491FF"
							title="审核意见"
							style="cursor: pointer; margin: 0 6px"
							@click="toComment(scope.row, true)"
						>
							<ChatLineSquare />
						</el-icon>
					</template>
				</el-table-column>
			</el-table>
			<div class="dialog-foot">
				<el-button @click="showUploadDialog = false">取消</el-button>
				<el-button type="primary" :disabled="uploadLoading" @click="handleOptionSubmit2(optionsFormRef1)">确认</el-button>
			</div>
		</cmDialog>
		<cmDialog v-model="showOptionsDialog" modal-title="评审意见" model-width="800px">
			<el-form ref="optionsFormRef" :model="optionsInfo" :rules="optionRules" label-width="180px">
				<el-row>
					<el-form-item label="意见附件类型" style="width: 100%">
						<el-radio-group v-model="optionsInfo.stage" :disabled="optionsDisabled" @change="uploadTypeChange">
							<el-radio v-for="(item, index) in optionsList" :key="index" :value="item.value" size="large">{{ item.name }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-row>
				<el-row>
					<el-form-item label="批复文件" style="width: 100%" prop="filesRecordList">
						<!-- <div
							v-for="(item, index) in optionsInfo.filesRecordList"
							:key="index"
							style="text-decoration: underline; margin-right: 20px; color: #1491ff; cursor: pointer"
							@click="handleUploadPdfPreview(item)"
						>
							{{ item.name }}
						</div> -->
						<el-upload
							ref="uploadPdfRef"
							drag
							:action="uploadApi"
							:headers="uploadHeaders"
							:data="uploadData"
							accept=".pdf"
							:on-success="handleUploadSuccess"
							:on-remove="handleUploadRemove"
							:file-list="optionsInfo.filesRecordList"
							:before-upload="beforeUploadPdf"
							:on-preview="handleUploadPdfPreview"
							:on-change="handleChange"
							:disabled="optionsDisabled"
						>
							<el-icon class="el-icon--upload"><upload-filled /></el-icon>
							<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
						</el-upload>
					</el-form-item>
				</el-row>
				<el-row v-if="currentStage == '1'">
					<!-- <el-row v-if="optionsInfo.stage == currentStage && currentPermission == '1' && showUploadType == 1"></el-row> -->
					<el-form-item label="是否有管理文件、具体措施" style="width: 100%" prop="hasDocument">
						<el-radio-group v-model="optionsInfo.hasDocument" :disabled="optionsDisabled">
							<el-radio :value="'1'" size="large">有</el-radio>
							<el-radio :value="'0'" size="large">无</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-row>
				<el-row v-if="optionsInfo.hasDocument == '1'">
					<!-- <el-row v-if="optionsInfo.stage == currentStage && currentPermission == '1' && showUploadType == 1 && optionsInfo.hasDocument == '1'"></el-row> -->
					<el-form-item label="具体内容" style="width: 100%" prop="documentContent">
						<el-input
							v-model="optionsInfo.documentContent"
							type="textarea"
							:rows="3"
							style="width: 100%"
							maxlength="500"
							show-word-limit
							:disabled="optionsDisabled"
						></el-input>
					</el-form-item>
				</el-row>
				<el-row v-if="currentStage == '3' || isRepublish">
					<el-form-item label="批文年度" prop="approvalFileYear">
						<el-date-picker
							v-model="optionsInfo.approvalFileYear"
							type="year"
							format="YYYY"
							value-format="YYYY"
							placeholder="选择年份"
							style="width: 240px"
							:disabled="optionsDisabled"
						/>
					</el-form-item>
					<el-form-item label="文号" prop="approvalFileNumber">
						<el-input v-model="optionsInfo.approvalFileNumber" type="number" placeholder="请输入" style="width: 240px" :disabled="optionsDisabled" />
					</el-form-item>
				</el-row>
				<el-row>
					<!-- <el-row v-if="optionsInfo.stage == currentStage && currentPermission == '1' && showUploadType == 1"></el-row> -->
					<el-form-item label="备注说明" style="width: 100%" prop="opinions">
						<el-input
							v-model="optionsInfo.opinions"
							type="textarea"
							:rows="3"
							style="width: 100%"
							maxlength="500"
							show-word-limit
							:disabled="optionsDisabled"
						></el-input>
					</el-form-item>
				</el-row>
			</el-form>
			<div class="dialog-foot">
				<el-button @click="showOptionsDialog = false">取消</el-button>
				<el-button v-if="optionsDisabled == false" type="primary" @click="handleOptionSubmit(optionsFormRef)">确定</el-button>
			</div>
		</cmDialog>
		<addDialog v-model="showAddDialog" :edit-id="editId" :is-view="true" :info="standardInfo" :is-audit="true"></addDialog>
	</el-card>
</template>
<script setup lang="ts">
import { addOptions, batchAudit, batchUploadFiles, cancelPublish, getList, getOptions, getStage, republishProject } from '@/api/fushen/audit'
import { filePreviewByName } from '@/api/sys/upload'
import cmDialog from '@/components/cm-dialog/index.vue'
import { StandardInfo } from '@/interface/review'
import { router } from '@/router'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import type { FormInstance, TableInstance, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import addDialog from '../components/addDialog.vue'

const route = useRoute()
const pendingStatus = route.query.pendingStatus

const userStore = useUserStore()
const dictionaryStore = useDictionaryStore()
const reviewStatus = dictionaryStore.getDictionaryByCode('T015')
const reviewResult = dictionaryStore.getDictionaryByCode('T0035')
const reviewStage = dictionaryStore.getDictionaryByCode('T0026')
const handleResult = dictionaryStore.getDictionaryByCode('T0035')
const handleResult1 = dictionaryStore.getDictionaryByCode('T016')
// const handleResult = [
// 	{
// 		label: '拟继续有效三年',
// 		value: '1'
// 	},
// 	{
// 		label: '拟暂定有效一年',
// 		value: '2'
// 	},
// 	{
// 		label: '拟应予修订',
// 		value: '3'
// 	},
// 	{
// 		label: '拟废除',
// 		value: '4'
// 	}
// ]
const codeMap = {
	'1': 'ZGBM_ReviewApprove',
	'2': 'ZJZZ_ReviewApprove',
	'3': 'ZJWSH_ReviewApprove'
}

const state = reactive({
	queryForm: {
		standardNumber: '',
		standardProjectName: '',
		responsiblePerson: '',
		contactName: '',
		applyYear: '',
		reviewAddtype: '',
		reviewYear: '',
		userName: '',
		reviewStage: [],
		reviewStatus: [],
		remark: [],
		pendingStatus: pendingStatus || ''
	},
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false,
	keyType: '',
	keyword: null
})
const dataList = ref([])
const showAddDialog = ref<boolean>(false)
const editId = ref<string>('')
const standardInfo = ref<StandardInfo | null>(null)
const multipleTableRef = ref<TableInstance>()
const showOptionsDialog = ref<boolean>(false)
const optionsFormRef = ref<FormInstance>()
const optionsFormRef1 = ref<FormInstance>()
const optionsInfo = reactive({
	id: '',
	opinions: '',
	hasDocument: '0',
	documentContent: '',
	stage: '',
	filesRecordList: [],
	approvalFileYear: '',
	approvalFileNumber: ''
})
const optionsRules = reactive<any>({
	approvalFileYear: [{ required: true, message: '请选择年份', trigger: 'blur' }],
	approvalFileNumber: [{ required: true, message: '请输入文号', trigger: 'blur' }],
	filesRecordList: [
		{
			required: true,
			validator: (rule, value, callback) => {
				if (value && value.length > 0) {
					callback() // 验证通过
				} else {
					callback(new Error('请上传文件')) // 验证失败
				}
			}
		}
	]
})
const optionRules = reactive<any>({
	opinions: [{ required: true, message: '请填写备注说明', trigger: 'blur' }],
	documentContent: [
		{
			validator: (rule: any, value: string, callback: Function) => {
				if (optionsInfo.hasDocument === '1' && !value) {
					callback(new Error('请填写具体内容'))
				} else {
					callback()
				}
			},
			trigger: 'blur'
		}
	],
	approvalFileYear: [{ required: true, message: '请选择年份', trigger: 'blur' }],
	approvalFileNumber: [{ required: true, message: '请输入文号', trigger: 'blur' }],
	filesRecordList: [
		{
			required: true,
			validator: (rule, value, callback) => {
				if (value && value.length > 0) {
					callback() // 验证通过
				} else {
					callback(new Error('请上传文件')) // 验证失败
				}
			}
		}
	]
})
const uploadList = ref([])
const currentStage = ref('')
const currentPermission = ref('')
const optionsList = ref([])
const uploadApi = `${import.meta.env.MODE === 'development' ? 'http://220.196.89.86:9173' : window.location.protocol + '//' + window.location.host}/JGBStandardWebApi/api/files/upload`
const uploadHeaders = {
	Authorization: userStore.token
}
const uploadData = ref({
	extCode: '',
	remark: '审批附件(pdf)'
})
const showUploadType = ref(1)
const selectList = ref([])
const returnBackInfo = ref({
	id: '',
	codeType: 'StandardApply',
	remark: ''
})
const showUploadDialog = ref(false)
const uploadIds = ref([])

const uploadLoading = ref(false)

const isRepublish = ref(false)

const optionsDisabled = ref(false)

const hasPermission = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => row.permission == 1)
	// const firstApplyStage = selectedRows[0].applyStage
	// const allApplyStageSame = selectedRows.every(row => row.applyStage === firstApplyStage)

	return allPermissionValid
})

const hasUploadPermission = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}
	const allPermissionValid = selectedRows.every(row => (row.permission == 1 || row.permission == 2) && row.reviewStatus != '3')
	// const firstApplyStage = selectedRows[0].applyStage
	// const allApplyStageSame = selectedRows.every(row => row.applyStage === firstApplyStage)

	return allPermissionValid
})

const hasPublish = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => row.reviewStatus == 3)

	return allPermissionValid
})

const hasUnPublish = computed(() => {
	if (!multipleTableRef.value) {
		return false
	}
	const selectedRows = multipleTableRef.value.getSelectionRows()

	if (selectedRows.length === 0) {
		return false
	}

	const allPermissionValid = selectedRows.every(row => row.reviewStatus == 4)

	return allPermissionValid
})

const getDataList = () => {
	state.queryForm.standardNumber = ''
	state.queryForm.standardProjectName = ''
	state.queryForm.responsiblePerson = ''
	state.queryForm.contactName = ''
	state.queryForm.userName = ''
	if (state.keyword && !state.keyType) {
		ElMessage.error('请选择关键词类型')
		return
	}
	switch (state.keyType) {
		case '1':
			state.queryForm.standardNumber = state.keyword
			break
		case '2':
			state.queryForm.standardProjectName = state.keyword
			break
		case '3':
			state.queryForm.responsiblePerson = state.keyword
			break
		case '4':
			state.queryForm.contactName = state.keyword
			break
		case '5':
			state.queryForm.userName = state.keyword
			break
	}
	state.dataListLoading = true
	getList({
		pageIndex: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		const list = res.data.list
		state.dataListLoading = false
		dataList.value = []
		if (list.length > 0) {
			list.forEach((item, index) => {
				dataList.value.push({
					index: index + 1,
					...item
				})
			})
		}
		state.total = res.data.total || 0
	})
}
const search = () => {
	state.pageNum = 1
	getDataList()
}

const reset = () => {
	state.queryForm.standardNumber = ''
	state.queryForm.standardProjectName = ''
	state.queryForm.responsiblePerson = ''
	state.queryForm.contactName = ''
	state.queryForm.userName = ''
	state.queryForm.applyYear = ''
	state.queryForm.reviewAddtype = ''
	state.queryForm.reviewYear = ''
	state.queryForm.reviewStage = []
	state.queryForm.reviewStatus = []
	state.queryForm.remark = []
	state.queryForm.pendingStatus = ''
	state.keyword = null
	state.keyType = ''
	state.pageNum = 1
	getDataList()
}

watch(
	() => showUploadDialog.value,
	newVal => {
		if (newVal == false) {
			optionsInfo.id = ''
			optionsInfo.opinions = ''
			optionsInfo.hasDocument = '0'
			optionsInfo.documentContent = ''
			optionsInfo.stage = ''
			optionsInfo.filesRecordList = []
			uploadList.value = []
			showUploadType.value = 1
			selectList.value = []
			uploadIds.value = []
			isRepublish.value = false
			optionsInfo.approvalFileYear = ''
			optionsInfo.approvalFileNumber = ''
			optionsFormRef1.value.clearValidate()
		}
	}
)

watch(
	() => showAddDialog.value,
	newVal => {
		if (!newVal) {
			standardInfo.value = null
			editId.value = ''
		}
	}
)

watch(
	() => showOptionsDialog.value,
	newVal => {
		if (newVal == false) {
			optionsInfo.id = ''
			optionsInfo.opinions = ''
			optionsInfo.hasDocument = '0'
			optionsInfo.documentContent = ''
			// optionsInfo.stage = ''
			// optionsInfo.filesRecordList = []
			uploadList.value = []
			showUploadType.value = 1
			// selectList.value = []
			uploadIds.value = []
			isRepublish.value = false
			optionsInfo.approvalFileYear = ''
			optionsInfo.approvalFileNumber = ''
			optionsFormRef.value.clearValidate()
			optionsDisabled.value = false
		}
	}
)

const handleUploadPdfPreview = (ruploadFile: any) => {
	if (ruploadFile.systemFileName) {
		filePreviewByName(ruploadFile.systemFileName).then(res => {
			window.open(res.data.url)
		})
	} else {
		filePreviewByName(ruploadFile?.response.data.systemFileName).then(res => {
			window.open(res.data.url)
		})
	}
}

const detailHandle = (row: any) => {
	standardInfo.value = row
	editId.value = row.id
	showAddDialog.value = true
}

const toComment = async (row: any, type: boolean) => {
	optionsDisabled.value = type
	showOptionsDialog.value = true
	optionsInfo.id = row.id
	currentPermission.value = row.permission
	optionsInfo.hasDocument = row.hasDocument
	await getCurrentStage(row.id)
	await getComment()
}

const getComment = async () => {
	await getOptions({
		id: optionsInfo.id,
		stage: optionsInfo.stage
	}).then(res => {
		optionsInfo.opinions = res.data.opinions || ''
		if (res.data.hasDocument != null) {
			optionsInfo.hasDocument = res.data.hasDocument
		} else {
			optionsInfo.hasDocument = '0'
		}
		optionsInfo.documentContent = res.data.documentContent || ''
		uploadList.value = res.data.filesRecordList || []
		let fileList = JSON.parse(JSON.stringify(uploadList.value))
		fileList.forEach((file: any) => {
			file.name = file.fileRealName + '.' + file.fileExtName
		})
		optionsInfo.filesRecordList = fileList
		if (res.data.approvalFileYear) {
			optionsInfo.approvalFileYear = res.data.approvalFileYear.toString()
		} else {
			optionsInfo.approvalFileYear = ''
		}
		optionsInfo.approvalFileNumber = res.data.approvalFileNumber || ''
	})
}

const getCurrentStage = async (id: string) => {
	await getStage({
		id: id
	}).then(res => {
		const nodeList = res.data[0].nodeList
		optionsList.value = nodeList
		currentStage.value = res.data[0].stage.toString()
		optionsInfo.stage = JSON.parse(JSON.stringify(currentStage.value))
		uploadData.value.extCode = codeMap[currentStage.value]
	})
}

const uploadTypeChange = () => {
	uploadData.value.extCode = codeMap[optionsInfo.stage]
	getComment()
}

const beforeUploadPdf = (file: UploadRawFile) => {
	const allowedTypes = ['application/pdf']
	const fileExtension = file.name.split('.').pop()?.toLowerCase()
	if (!allowedTypes.includes(file.type) || fileExtension !== 'pdf') {
		ElMessage.error('仅支持上传 PDF 文件')
		return false
	}
	uploadLoading.value = true
	return true
}

const handleChange = (file: UploadRawFile, fileList: any) => {
	optionsInfo.filesRecordList = []
	fileList.forEach((file: any) => {
		if (file.response) {
			optionsInfo.filesRecordList.push(file.response.data)
		} else {
			optionsInfo.filesRecordList.push(file)
		}
	})
	optionsInfo.filesRecordList.forEach((file: any) => {
		file.name = file.fileRealName
	})
}

const handleUploadSuccess = (res: any, uploadFile: any) => {
	uploadLoading.value = false
	if (res.code == '200') {
		uploadList.value.push(res.data)
		if (showUploadDialog.value) {
			optionsFormRef1.value.clearValidate('filesRecordList')
		} else {
			optionsFormRef.value.clearValidate('filesRecordList')
		}
		// saveUpload()
	}
}

const saveUpload = () => {
	batchUploadFiles({
		ids: uploadIds.value,
		filesRecordList: uploadList.value
	}).then(res => {
		console.log(res)
	})
}

const handleUploadRemove = (file: any) => {
	const id = file.response ? file.response.data.id : file.id
	uploadList.value = uploadList.value.filter((item: any) => item.id !== id)
	optionsInfo.filesRecordList = optionsInfo.filesRecordList.filter((item: any) => item.id !== file.id)
	// saveUpload()
}

const handleOptionSubmit2 = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			const api = isRepublish.value ? republishProject : batchUploadFiles
			let fileList = []
			uploadList.value.forEach((file: any) => {
				fileList.push({
					extCode: file.extCode,
					fileExtName: file.fileExtName,
					filePath: file.filePath,
					fileRealName: file.fileRealName,
					fileSize: file.fileSize,
					id: file.id,
					remark: file.remark,
					systemFileName: file.systemFileName
				})
			})
			api({
				ids: uploadIds.value,
				filesRecordList: fileList,
				approvalFileYear: optionsInfo.approvalFileYear,
				approvalFileNumber: optionsInfo.approvalFileNumber
			}).then(res => {
				if (isRepublish.value) {
					getDataList()
				}
				showUploadDialog.value = false
				ElMessage.success('提交成功')
			})
		} else {
			console.log('error submit!', fields)
		}
	})
}

const handleOptionSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			let fileList = []
			uploadList.value.forEach((file: any) => {
				fileList.push({
					extCode: file.extCode,
					fileExtName: file.fileExtName,
					filePath: file.filePath,
					fileRealName: file.fileRealName,
					fileSize: file.fileSize,
					id: file.id,
					remark: file.remark,
					systemFileName: file.systemFileName
				})
			})
			addOptions({
				id: optionsInfo.id,
				stage: optionsInfo.stage,
				opinions: optionsInfo.opinions,
				hasDocument: optionsInfo.hasDocument,
				documentContent: optionsInfo.documentContent,
				filesRecordList: fileList,
				approvalFileYear: optionsInfo.approvalFileYear,
				approvalFileNumber: optionsInfo.approvalFileNumber
			}).then(() => {
				showOptionsDialog.value = false
				ElMessage.success('审核意见提交成功')
				getDataList()
			})
		} else {
			console.log('error submit!', fields)
		}
	})
}

const submitHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}
		const unprocessedIndices = []
		selectedRows.forEach((row, index) => {
			if (!row.status) {
				if (!row.status) {
					unprocessedIndices.push(row.index)
				}
			}
		})
		if (unprocessedIndices.length > 0) {
			throw new Error(`序号为${unprocessedIndices.join('、')}的数据未处理，请检查！`)
		}
		const tableList = []
		selectedRows.forEach(row => {
			tableList.push({
				id: row.id,
				status: row.status
			})
		})
		ElMessageBox.confirm(`是否需要上传审核意见，如果需要请先单个选择项目填写意见？`, '温馨提示', {
			confirmButtonText: '直接提交审核',
			cancelButtonText: '去上传审核意见',
			type: 'warning'
		})
			.then(() => {
				batchAudit({ tableList: tableList }).then(() => {
					ElMessage.success('操作成功')
					getDataList()
				})
			})
			.catch(() => {})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const uploadFileHandle = async () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}
		const firstStage = selectedRows[0].reviewStage
		const allStageSame = selectedRows.every(row => row.reviewStage === firstStage)
		if (!allStageSame) {
			throw new Error('请选择相同审核阶段的项目')
		}
		// if (firstStage == '4') {
		// 	throw new Error('所选项目已复审完毕，无需上传附件')
		// }
		selectList.value = selectedRows
		// selectList.value.forEach((row, index) => {
		// 	row.hasDocument = '0'
		// })
		showUploadDialog.value = true
		uploadIds.value = selectedRows.map(item => {
			return item.id
		})
		uploadData.value.extCode = codeMap[selectedRows[0].reviewStage]
		optionsInfo.id = selectedRows[0].id
		await getCurrentStage(uploadIds.value[0])
		await getComment()
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const handleReturnBack = (item: any) => {
	returnBackInfo.value.id = item.id
	ElMessageBox.confirm(`是否退回项目'${item.standardProjectName}'？`, '温馨提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			batchAudit({
				tableList: [
					{
						id: returnBackInfo.value.id,
						status: '8'
					}
				]
			}).then(() => {
				ElMessage.success('操作成功')
				getDataList()
			})
		})
		.catch(() => {})
}

const handleReturnBackSubmit = () => {
	if (returnBackInfo.value.remark == '') {
		ElMessage.error('退回原因不能为空')
		return
	}
}

const createListHandle = () => {}

const exportHandle = () => {
	try {
		// const selectedRows = multipleTableRef.value.getSelectionRows()
		// if (selectedRows.length == 0) {
		// 	throw new Error('请选择一个项目')
		// }
		// const ids = selectedRows.map(item => {
		// 	return item.id
		// })
		const param = {
			// processor: '',
			// projectId: ids.toString(),
			...state.queryForm
		}
		axios({
			method: 'post',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/review/exportReview',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			data: param,
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = '复审项目导出文件.xls'
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const cancelHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请选择一个项目')
		}
		// if (selectedRows.length > 1) {
		// 	throw new Error('只能选择一个项目')
		// }
		ElMessageBox.confirm(`确定取消发布该项目吗？`, '温馨提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				const ids = selectedRows.map(item => {
					return item.id
				})
				cancelPublish({
					ids: ids
				}).then(() => {
					ElMessage.success('操作成功')
					getDataList()
				})
			})
			.catch(() => {})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const republishHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}
		isRepublish.value = true
		selectList.value = selectedRows
		uploadData.value.extCode = 'ZJWSH_ReviewApprove'
		optionsInfo.id = selectedRows[0].id
		optionsInfo.stage = selectedRows[0].applyStage
		showUploadDialog.value = true
		uploadIds.value = selectedRows.map(item => {
			return item.id
		})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const addOrUpdateHandle = () => {
	router.push({
		path: '/Reexamine/score/index'
	})
}
const selectionChangeHandle = () => {}
const sizeChangeHandle = (e: number) => {
	state.pageSize = e
	state.pageNum = 1
	getDataList()
}
const currentChangeHandle = (e: number) => {
	state.pageNum = e
	getDataList()
}
const getDataListParent = () => {}

onMounted(() => {
	getDataList()
})
</script>
<style lang="scss" scoped>
.anniu .el-form-item {
	margin-right: 10px !important;
}

.dialog-foot {
	display: flex;
	justify-content: center;
	padding-top: 20px;
	margin-bottom: 10px;
}

.resizable-table .el-table__cell {
	border-right: 1px solid #aebee2 !important;
}
</style>
